GeeKee CeeBee

Welcome to GeeKee CeeBee's Page: House of Mechatronics & Controls Engineering Projects

(PYTHON) Differential Eq. using Finite Difference Method in Discrete Time





Step-by-step video












PYTHON Code

    

# By GeeKee CeeBee  https://www.youtube.com/watch?v=joHX2vJiEQI&feature=youtu.be
# Solve Differential Using Finite Difference Method in Discrete Time
# This example looks at Spring Mass Damper System

# Import libraries
import numpy
import matplotlib.pyplot as plt

K = 1000                               # Spring Constant
M = 10                                 # Mass
C = 200                                # Damping Constant
dt= 0.001                              # Define Time Step
t = numpy.arange(0, 5, dt)             # Define Time range
y = numpy.ones(len(t))                 # Unit Step function
y[0:1000] = 0
y[1000:5000] = 0.1
x = numpy.zeros(len(t))
x[0]=0                                  # Initial Condition
x[1]=0

A1 = (C / dt) + (M / dt ** 2) + K
A2 = (-2 * M / dt ** 2) - (C / dt)
A3 = (M / dt ** 2)
A4 = (C / dt) + K
A5 = (-C / dt)

for k in range(2, len(t)):
    x[k] = (1 / A1) * (A4 * y[k] + A5 * y[k - 1] - A2 * x[k - 1] - A3 * x[k - 2])

t = dt * numpy.arange(0, len(t))
plt.figure(1)
plt.plot(t, x, t, y,linewidth=2.0)
plt.xlabel('Time')
plt.ylabel('Displacement')
plt.gca().legend(('x(t)','y(t)'))
plt.title('Displacement vs Time')
plt.show()